﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using FM_Mono;
using Unity.Collections.LowLevel.Unsafe;

[IgnoreGen]
public class MeshRendererResourceCollector :MonoBehaviour
{
	public MeshRenderer[] renderers;
	public int[] materialIndexArr;
	public int[] meshIndexArr;
	public Material[] materials;
	public Mesh[] meshes;

	// Use this for initialization
	void Start()
	{
		int count = renderers != null ? renderers.Length : 0;
		for (int i = 0; i < count; ++i)
		{
			MeshRenderer render = renderers[i];
			MeshFilter filter = render.GetComponent<MeshFilter>();
			render.sharedMaterial = materials[materialIndexArr[i]];
			filter.sharedMesh = meshes[meshIndexArr[i]];
		}
	}

	[ContextMenu("Execute")]
	void CollectResource()
	{
		renderers = GetComponentsInChildren<MeshRenderer>();
		int count = renderers != null ? renderers.Length : 0;
		List<Material> matList = new List<Material>();
		List<Mesh> meshList = new List<Mesh>();
		if (count > 0)
		{
			materialIndexArr = new int[count];
			meshIndexArr = new int[count];

			for (int i = 0; i < count; ++i)
			{
				MeshRenderer renderer = renderers[i];
				MeshFilter filter = renderer.GetComponent<MeshFilter>();
				int index = matList.IndexOf(renderer.sharedMaterial);
				if (index == -1)
				{
					index = matList.Count;
					matList.Add(renderer.sharedMaterial);
				}
				materialIndexArr[i] = index;
				renderer.sharedMaterial = null;

				index = meshList.IndexOf(filter.sharedMesh);
				if (index == -1)
				{
					index = meshList.Count;
					meshList.Add(filter.sharedMesh);
				}
				meshIndexArr[i] = index;
				filter.sharedMesh = null;
			}
			materials = matList.ToArray();
			meshes = meshList.ToArray();
		}
	}
}
